<?php

namespace Home\Controller;

use Think\Controller;

class OrderController extends CommonController
{
    /***
     * 加载首页
     */
    public function index()
    {
        $id = $_SESSION['customer']['id'];
        $address = $this->address->where("customer_id = '$id'")->find();
        $carts = $this->cart->where("customer_id = '$id'")->select();
        $count = 0;
        foreach ($carts as &$cart) {
            $cart['child'] = $this->product->where("id = '$cart[product_id]'")->find();
            $count += floatval($cart['child']['price']) * intval($cart['num']);//总金额

        }

        $this->assign('carts', $carts);
        $this->assign('count', $count);
        $this->assign('address', $address);

        $this->display();
    }

    /***
     * 立刻下单新增
     */
    public function add()
    {
        $Order = M('Order');

        if (IS_AJAX) {

            $data['product_id'] = I('post.product_id');
            $data['order_id'] = $_SESSION['customer']['id'];

            if (!$_SESSION['customer']) {
                $info = array('status' => 0, 'msg' => '请登录');
            } else {
                $Order->add($data);
            }
            $this->ajaxReturn($info);
        }
    }

    /***
     * 新增地址
     */
    public function add_address()
    {

        if (IS_AJAX) {
            $data['customer_id'] = $this->customer_id;
            $data['name'] = trim(I('post.name'));
            $data['tel'] = I('post.tel');
            $data['area'] = I('post.area');
            $data['detail'] = I('post.detail');
            $face = array('status' => 1, 'msg' => '新增成功');
            $telephone = "/^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$/";

            if (strlen($data['name']) < 3) {
                $face = array('status' => 0, 'msg' => '名字不能小于3位');
            }
            if (!preg_match($telephone, $data['tel'])) {
                $face = array('status' => 0, 'msg' => '输入手机格式不正确');
            }
            if ($face['status'] == 1) {
//                $this->address->create();
                $this->address->add($data);

            }
            $this->ajaxReturn($face);

        }
    }
    /***
     * 下单
     */
//    public function confirm(){
//        $id = $_SESSION['customer']['id'];
//        $orders = $this->order->where("customer_id = '$id'")->select();
//        $order = $this->order->where("customer_id = '$id'")->find();
//        foreach ($orders as &$order){
//            $order['address'] = $this->address->where("id = '$order[address_id]'")->find();
//        }
//        $carts = $this->cart->where("customer_id = '$id'")->select();
//        $count=0;
//
//        foreach ($carts as &$cart) {
//            $cart['child'] = $this->product->where("id = '$cart[product_id]'")->find();
//            $count += floatval($cart['child']['price']) * intval($cart['num']);//总金额
//
//        }
//
//
//        $this->assign(compact('orders','carts','count','order'));
//        $this->display();
//    }

    public function store()
    {
        //连表（a:cart表；b：product表）查出商品信息
        $products = $this->cart->alias('a')->field('a.id as cart_id,a.num,b.*')
            ->join('product as b ON b.id=a.product_id', 'LEFT')
            ->where(['a.customer_id' => $this->customer_id])->select();

        $total = 0;
        foreach ($products as $k => $v) {
            $total += floatval($v['price']) * intval($v['num']);

            //判断商品库存
            if (intval($v['num']) > intval($v['stock'])) {
                $info=array('status'=>0,'msg'=>'此商品库存不足');
                $this->ajaxReturn($info);
//                $this->error('此商品库存不足');
            }
        }
        $carts = $this->cart->where("customer_id = '$this->customer_id'")->select();
        if (!$carts) {
            $info = array('status'=>3,'msg'=>'当前订单已提交');
            $this->ajaxReturn($info);
        }

        //生成订单
        $data = [];
        $data['customer_id'] = $this->customer_id;
        $data['order_no'] = make_token();
        $data['created_at'] = time();
        $data['total_price'] = $total;
        $data['address_id'] = I('post.address_id');
        $data['status'] = 1;  //初始状态为1
        //订单数据插入订单表
        $id = $this->order->add($data);


        if ($id) {

            $orderProductInfo['order_id'] = $id;

            //插入订单商品表的数据
            foreach ($products as $k => $v) {
                $orderProductInfo['product_id'] = $v['id'];
                $orderProductInfo['number'] = $v['num'];
                $this->order_product->add($orderProductInfo);
            }

            //支付成功后对应减去商品的库存及清空购物车
            $numbers = intval($orderProductInfo['number']);
            $product_id = $orderProductInfo['product_id'];
//            $this->product->where("id = '$product_id'")->setField('sale_done', $numbers);  //已售商品数量
            $this->product->where("id = '$product_id'")->setDec('stock', $numbers);  //减去库存
            $this->cart->where("customer_id = $this->customer_id")->delete();  //清空购物车
            $info = array('status' => 1, 'msg' => '您已成功下单');
            $info['id'] = $id;
        }
        else {

            $info = array('status' => 0, 'msg' => '下单失败');
        }
        $this->ajaxReturn($info);

    }

    public function confirm()
    {
        $id = I('get.id');
        $order_products = $this->order_product->where("order_id = '$id'")->select();
        foreach ($order_products as &$order_product) {
            $order_product['product'] = $this->product->where("id ='$order_product[product_id]'")->find();
        }

        $order = $this->order->where("id = '$id'")->find();
        $address = $this->address->where("id = '$order[address_id]'")->find();
        $this->assign(compact('order_products','order','address'));
        $this->display();
    }
}